iT邦幫忙

2024 iThome 鐵人賽

DAY 2
0
自我挑戰組

Leetcode 解題之旅:逐日攻克系列 第 2

每日一LeetCode(2)

  • 分享至 

  • xImage
  •  

20. Valid Parentheses

題目敘述

Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.

An input string is valid if:

1.Open brackets must be closed by the same type of brackets.
2.Open brackets must be closed in the correct order.
3.Every close bracket has a corresponding open bracket of the same type.

Example 1:
Input: s = "()"
Output: true

Example 2:
Input: s = "()[]{}"
Output: true

Example 3:
Input: s = "(]"
Output: false

程式碼(C++):

class Solution {
public:
    bool isValid(string s) {
        stack<char> st; 
        for (char c : s) 
        { 
            if (c == '(' || c == '{' || c == '[') 
            { 
                st.push(c); 
            } 
            else 
            { 
                if (st.empty() || 
                    (c == ')' && st.top() != '(') || 
                    (c == '}' && st.top() != '{') ||
                    (c == ']' && st.top() != '[')) 
                {
                    return false; 
                }
                st.pop(); 
            }
        }
            return st.empty(); 
    }
};

上一篇
每日一LeetCode(1)
下一篇
每日一LeetCode(3)
系列文
Leetcode 解題之旅:逐日攻克30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言